package com.iweb.dao;

import com.iweb.entity.User;
import com.iweb.role.UserType;
import com.iweb.transaction.TransactionManager;
import com.iweb.utitls.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ryl
 * @version 1.0
 * @data 2025/4/2 16:45
 */
public class UserDao {
    private TransactionManager transactionManager = new TransactionManager();
    public UserDao() throws Exception {
    }
    /**
     * 登录用户
     */
    public boolean loginUser(String username, String password) {
        String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
        JdbcUtil util = new JdbcUtil();
        try {
            Connection conn = util.getConn();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();
            return rs.next();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 判断用户是否存在
     * @param username
     * @return
     */
    public boolean existsUsername(String username) {
        String sql = "SELECT * FROM user WHERE username = ? ";
        JdbcUtil util = new JdbcUtil();
        try {
            Connection conn = util.getConn();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();
            return rs.next();
        } catch (Exception e) {
            return false;
        }
    }
    /**
     * 添加用户
     */
    public void addUser(User users) throws SQLException {
        String sql = "INSERT INTO user(username,password) values(?,?)";
        Connection conn = null;
        try {
            conn = transactionManager.beginTransaction();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, users.getUsername());
            ps.setString(2, users.getPassword());
            int result = ps.executeUpdate();
            if (result > 0) {
                System.out.println("注册成功!!!!");
            } else {
                System.out.println("注册失败....");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean existsUsernameAndPassword(String username, String password) {
        String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
        JdbcUtil util = new JdbcUtil();
        try {
            Connection conn = util.getConn();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();
            return rs.next();
        } catch (Exception e) {
            return false;
        }
    }
    /**
     * 删除用户
     * @param userName
     */
    public void deleteUser(String username) throws Exception {
        String sql = "DELETE FROM user WHERE username = ?";
        Connection conn = null;
        try {
            conn = transactionManager.beginTransaction();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            int result = ps.executeUpdate();
            if (result > 0) {
                System.out.println("删除成功!!!!");
            } else {
                System.out.println("删除失败....");
            }
            transactionManager.commit(conn);
        } catch (SQLException e) {
            if (conn != null) {
                transactionManager.rollback(conn);
            }
            throw new RuntimeException(e);
        }
    }

    /**
     * 更新密码
     * @param users
     */
    public void updateUser(User users) throws SQLException {
        String sql = "UPDATE user SET password = ? WHERE username = ?";
        Connection conn = null;
        try {
            conn = transactionManager.beginTransaction();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, users.getPassword());
            ps.setString(2, users.getUsername());
            int result = ps.executeUpdate();
            if (result > 0) {
                System.out.println("修改成功!!!!");
            } else {
                System.out.println("修改失败....");
            }
        } catch (SQLException e) {
            if (conn != null) {
                transactionManager.rollback(conn);
            }
            throw new RuntimeException(e);
        }
    }
    /**
     * 查询全部用户
     */
    public List<User> selectAllUsers() {
        String sql = "SELECT id,username,password FROM user;";
        List<User> userList = new ArrayList<>();
        JdbcUtil util = new JdbcUtil();
        try {
            Connection conn = util.getConn();
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while(rs.next()) {
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String password = rs.getString("password");
                User users = new User(id, username, password);
                userList.add(users);
            }
            for (User users : userList) {
                System.out.println(users);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return userList;
    }
    /**
     * 模糊查询
     * @param userName
     */
    public List<User>  selectUser(String username) {
        String sql = "SELECT id,username,password FROM user WHERE username LIKE ?;";
        List<User> userList = new ArrayList<>();
        JdbcUtil util = new JdbcUtil();
        try {
            Connection conn = util.getConn();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, "%" + username + "%");
            ResultSet rs = ps.executeQuery();
            while(rs.next()) {
                int id = rs.getInt("id");
                String userName = rs.getString("username");
                String password = rs.getString("password");
                User users = new User(id, userName, password);
                userList.add(users);
            }
            for (User users : userList) {
                System.out.println(users);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return userList;

    }

    /**
     * 分页查询
     * @param limit
     * @param offset
     */
    public List<User> selectUsersPaged(int limit, int offset) {
        String sql = "SELECT id,username,password FROM user LIMIT ? OFFSET ?";
        List<User> userList = new ArrayList<>();
        JdbcUtil util = new JdbcUtil();
        try {
            Connection conn = util.getConn();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setInt(1, limit);
            ps.setInt(2, offset);
            ResultSet rs = ps.executeQuery();
            while(rs.next()) {
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String password = rs.getString("password");
                User users = new User(id, username, password);
                userList.add(users);
            }
            for (User users : userList) {
                System.out.println(users);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return userList;

    }

    /**
     *获取用户身份
     * @param username
     * @return 返回身份类型
     */
    public UserType getUserType(String username) {
    String sql = "SELECT user_type FROM user WHERE username = ?";
        JdbcUtil util = new JdbcUtil();
    try {
        Connection conn = util.getConn();
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1,username);
        try (ResultSet rs = ps.executeQuery()) {
            if (rs.next()) {
                //获取字段信息
                String userType = rs.getString("user_type");
                return UserType.valueOf(userType);
            }
        }
    }catch (SQLException e){
        e.printStackTrace();
    }
    return null;
    }
}
